﻿using System.Threading.Tasks;
using System.Threading;
using Microsoft.Extensions.Hosting;
using System;
using Adp;
using Newtonsoft.Json.Linq;
using Yqd.Enm;
using Adp.Common;
using Yqd.Models;
using System.Linq;

namespace Yqd.Core
{
    public class AssignHostService : BackgroundService
    {
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            var ctx = Fn.GetService<YqdContext>();
            var ddService = Fn.GetService<DdService>();
            while (!stoppingToken.IsCancellationRequested)
            {
                if (DateTime.Now.Hour >= 8 && DateTime.Now.Minute >= 30)
                {
                    Logs.Warning<AssignHostService>("工作方案逾期报审提前3天开始提醒！");
                    var nt = DateTime.Now.Date;
                    var assigns = ctx.Yqd_Assign.Where(it => it.ReportLimit.Subtract(nt).Days <= 3).ToList();
                    var pIDs = ctx.Yqd_Scheme.Where(it => it.CheckStatus != 审核状态.退回).Select(it => it.AssignID).ToArray();
                    var tIDs = assigns.Where(it => it.ItemType == 事项类型.专项交办).Select(it => it.ItemID).ToArray();
                    var ys = ctx.Yqd_Supervise.Where(it => it.IsDel == 0).Select(it => new { it.SuperviseID, it.Content }).ToList();
                    var cs = ctx.Yqd_Coordinate.Where(it => it.IsDel == 0).Select(it => new { it.CoordinateID, it.Item }).ToList();
                    var xs = ctx.Yqd_ExactSupervise.Where(it=>!it.IsDel).Select(it => new { it.SuperviseID, it.Problem }).ToList();
                    var ts = ctx.Yqd_Task.Select(it => new { it.TaskID, it.TaskName }).ToList();
                    var sp = ctx.Yqd_SpecialSupervise.Where(it => !it.IsDel && tIDs.Contains(it.SuperviseID)).Select(it => new { it.TaskID, it.SuperviseID, it.TemplateID, it.TemplateData });
                    var ids = sp.Select(it => it.TemplateID).ToArray();
                    var tps = ctx.Yqd_SpecialTemplate.Where(it => ids.Contains(it.TemplateID)).Select(it => new { it.TemplateID, it.Fields }).ToList();
                    foreach (var r in assigns)
                    {
                        if (pIDs.Contains(r.AssignID) || (r.NotifyTime != null && r.NotifyTime.Value.Date == nt)) continue;
                        string headtitle = "", text = "";
                        推送类型 pushType = 推送类型.领导督导;
                        switch (r.ItemType)
                        {
                            case 事项类型.钉办督导:
                                var s = ys.FirstOrDefault(it => it.SuperviseID == r.ItemID);
                                if (s != null)
                                {
                                    headtitle = "领导督导";
                                    text = "督导意见:" + s.Content;
                                    pushType = 推送类型.领导督导;
                                }
                                else
                                {
                                    continue;
                                }
                                break;
                            case 事项类型.协同管理:
                                var c = cs.FirstOrDefault(it => it.CoordinateID == r.ItemID);
                                if (c != null)
                                {
                                    headtitle = "领导协调";
                                    text = "协调内容  " + c.Item;
                                }
                                else
                                {
                                    continue;
                                }
                                break;
                            case 事项类型.精准督查:
                                var es = xs.FirstOrDefault(it => it.SuperviseID == r.ItemID);
                                if (es != null)
                                {
                                    headtitle = "精准督查";
                                    text = "存在问题  " + es.Problem;
                                    pushType = 推送类型.精准督查;
                                }
                                else
                                {
                                    continue;
                                }
                                break;
                            case 事项类型.专项交办:
                                headtitle = "专项交办";
                                pushType = 推送类型.专项交办;
                                break;
                        }
                        var TaskName = "";
                        long tID = r.TaskID;
                        if (r.ItemType == 事项类型.专项交办)
                        {
                            tID = 0;
                            var p = sp.FirstOrDefault(it => it.SuperviseID == r.ItemID);
                            if (p != null)
                            {
                                var f = tps.FirstOrDefault(it => it.TemplateID == p.TemplateID);
                                var FieldID = "";
                                if (f != null && f.Fields.HasValue())
                                {
                                    var arr = JArray.Parse(f.Fields);
                                    var o = arr.FirstOrDefault(it => it["IsShow"] != null && it["IsShow"].ToString().ToLower() == "true");
                                    if (o == null) o = arr[0];
                                    FieldID = o["FieldID"]?.ToString()??"";
                                    TaskName += o["FieldName"]?.ToString() ?? "";
                                }
                                if (FieldID != "" && p.TemplateData.HasValue())
                                {
                                    TaskName += JObject.Parse(p.TemplateData)[FieldID]?.ToString() ?? "";
                                }
                            }
                            else
                            {
                                continue;
                            }
                        }
                        else
                        {
                            var task = ts.FirstOrDefault(it => it.TaskID == r.TaskID);
                            if (task != null) TaskName = task.TaskName;
                        }
                        //关闭通知
                        //var msg = ddService.Notification(r.LeadUnit, headtitle + "-逾期提醒", tID, "任务名称：" + TaskName, text + "\n工作方案即将或已逾期报审，请及时报送！", Ip: "27.151.0.55",pushType: pushType);
                        //Logs.Warning<AssignHostService>("工作方案逾期报审提前3天发了工作通知，返回值：" + msg);
                        r.NotifyTime = DateTime.Now;
                    }
                    var ret = ctx.SaveChanges();
                    Logs.Warning<AssignHostService>("工作方案逾期报审提前3天提醒完成！本次推送" + ret + "条。");
                }
                Thread.Sleep(60000);
                await Task.Delay((1000 * 60 * 60), stoppingToken);
            }
        }
    }
}
